<template>
	<view class="container">
		<!-- 地址列表 -->
		<scroll-view scroll-y class="address-list" v-if="addressList.length > 0">
			<view class="address-item" v-for="(item, index) in addressList" :key="index" @click="selectAddressItem(item)">
				<view class="address-info">
					<view class="address-header">
						<text class="name">{{item.name}}</text>
						<text class="phone">{{item.phone}}</text>
						<text v-if="item.is_default" class="default-tag">默认</text>
					</view>
					<view class="address-detail">
						<text>{{item.province}} {{item.city}} {{item.district}} {{item.address}}</text>
					</view>
				</view>
				<view class="address-actions">
					<view class="action-item" @click.stop="setDefault(item.id, index)">
						<u-icon :name="item.is_default ? 'star-fill' : 'star'" :color="item.is_default ? '#007aff' : '#999'" size="40"></u-icon>
						<text>默认</text>
					</view>
					<view class="action-item" @click.stop="editAddress(item, index)">
						<u-icon name="edit-pen" color="#999" size="40"></u-icon>
						<text>编辑</text>
					</view>
					<view class="action-item" @click.stop="deleteAddress(item.id, index)">
						<u-icon name="trash" color="#999" size="40"></u-icon>
						<text>删除</text>
					</view>
				</view>
			</view>
		</scroll-view>
		
		<!-- 空地址列表 -->
		<view class="empty-address" v-else>
			<image src="/static/images/empty_address.png"  class="empty-image"></image>
			<text class="empty-text">您还没有添加地址</text>
		</view>
		
		<!-- 添加地址按钮 -->
		<view class="add-btn" @click="addAddress">添加新地址</view>
		
		<!-- 地址表单弹窗 -->
		<u-popup v-model="showAddressForm" mode="bottom" border-radius="16">
			<view class="address-form">
				<view class="form-header">
					<text>{{formTitle}}</text>
					<u-icon name="close" @click="closeForm" size="40"></u-icon>
				</view>
				
				<view class="form-content">
					<view class="form-item">
						<text class="label">收货人</text>
						<input class="input" v-model="addressForm.name" placeholder="请输入收货人姓名" />
					</view>
					
					<view class="form-item">
						<text class="label">手机号码</text>
						<input class="input" v-model="addressForm.phone" placeholder="请输入手机号码" type="number" maxlength="11" />
					</view>
					
					<view class="form-item">
						<text class="label">所在地区</text>
						<view class="region-picker" @click="openRegionPicker">
							<text v-if="addressForm.province">{{addressForm.province}} {{addressForm.city}} {{addressForm.district}}</text>
							<text v-else class="placeholder">请选择所在地区</text>
						</view>
					</view>
					
					<view class="form-item">
						<text class="label">详细地址</text>
						<textarea class="textarea" v-model="addressForm.address" placeholder="请输入详细地址" />
					</view>
					
					<view class="form-item">
						<label class="checkbox-label">
							<switch :checked="addressForm.is_default" @change="addressForm.is_default = !addressForm.is_default" color="#007aff" />
							<text>设为默认地址</text>
						</label>
					</view>
				</view>
				
				<view class="form-footer">
					<button class="save-btn" @click="saveAddress">保存地址</button>
				</view>
			</view>
		</u-popup>
		
		<!-- 地区选择器 -->
		<u-picker v-model="showRegionPicker" mode="region" @confirm="onRegionConfirm"></u-picker>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				addressList: [],
				showAddressForm: false,
				showRegionPicker: false,
				formTitle: '添加地址',
				editIndex: -1,
				isSelect: false,
				addressForm: {
					name: '',
					phone: '',
					province: '山东省',
					city: '青岛市',
					district: '',
					address: '',
					is_default: false,
					member_user_id : ''
				},
				userId: ''
			}
		},
		onLoad(options) {
			// 判断是否从订单确认页进入选择地址
			if (options.select) {
				this.isSelect = true;
			}
			
			// 获取用户ID
			this.getUserId();
			
			// 加载地址列表
			this.loadAddressList();
		},
		methods: {
			// 获取用户ID
			getUserId() {
				// 从本地存储获取用户信息
				const userInfo = uni.getStorageSync('userInfo');
				if (userInfo && userInfo.id) {
					this.userId = userInfo.id;
					this.addressForm.member_user_id  = userInfo.id;
				} else {
					// 测试用，实际应该跳转到登录页面
					this.userId = 1;
					this.addressForm.member_user_id  = 1;
				}
			},
			
			// 加载地址列表
			loadAddressList() {
				uni.showLoading({
					title: '加载中...'
				});
				
				// 调用API获取地址列表
				this.$api.getUserAddressList({ member_user_id : this.userId })
					.then(res => {
						this.addressList = res;
						uni.hideLoading();
					})
					.catch(err => {
						console.error('获取地址列表失败:', err);
						uni.hideLoading();
						
						// 如果API请求失败，尝试从本地存储获取
						const addressList = uni.getStorageSync('addressList') || [];
						this.addressList = addressList;
						
						uni.showToast({
							title: '获取地址列表失败',
							icon: 'none'
						});
					});
			},
			
			// 添加新地址
			addAddress() {
				this.formTitle = '添加地址';
				this.editIndex = -1;
				
				// 重置表单
				this.resetForm();
				
				// 显示表单
				this.showAddressForm = true;
			},
			
			// 编辑地址
			editAddress(item, index) {
				this.formTitle = '编辑地址';
				this.editIndex = index;
				
				// 填充表单
				this.addressForm = {
					id: item.id,
					name: item.name,
					phone: item.phone,
					province: item.province,
					city: item.city,
					district: item.district,
					address: item.address,
					is_default: item.is_default,
					member_user_id : this.userId
				};
				
				// 显示表单
				this.showAddressForm = true;
			},
			
			// 关闭表单
			closeForm() {
				this.showAddressForm = false;
			},
			
			// 重置表单
			resetForm() {
				this.addressForm = {
					name: '',
					phone: '',
					province: '',
					city: '',
					district: '',
					address: '',
					is_default: false,
					member_user_id : this.userId
				};
			},
			
			// 显示地区选择器
			openRegionPicker() {
				this.showRegionPicker = true;
			},
			
			// 地区选择器确认
			onRegionConfirm(e) {
                console.log(e);
				const { province, city, area } = e;
				this.addressForm.province = province.label;
				this.addressForm.city = city.label;
				this.addressForm.district = area.label;
			},
			
			// 保存地址
			saveAddress() {
				// 表单验证
				if (!this.addressForm.name) {
					uni.showToast({
						title: '请输入收货人姓名',
						icon: 'none'
					});
					return;
				}
				
				if (!this.addressForm.phone) {
					uni.showToast({
						title: '请输入手机号码',
						icon: 'none'
					});
					return;
				}
				
				if (!/^1\d{10}$/.test(this.addressForm.phone)) {
					uni.showToast({
						title: '手机号码格式不正确',
						icon: 'none'
					});
					return;
				}
				
				if (!this.addressForm.province) {
					uni.showToast({
						title: '请选择所在地区',
						icon: 'none'
					});
					return;
				}
				
				if (!this.addressForm.address) {
					uni.showToast({
						title: '请输入详细地址',
						icon: 'none'
					});
					return;
				}
				
				uni.showLoading({
					title: '保存中...'
				});
				
				// 编辑或添加地址
				if (this.editIndex > -1 && this.addressForm.id) {
					// 编辑
					this.$api.updateAddress(this.addressForm.id, this.addressForm)
						.then(() => {
              this.loadAddressList()
              uni.hideLoading();
              this.closeForm();
              // 提示
              uni.showToast({
                title: '保存成功',
                icon: 'success'
              });
						})
						.catch(err => {
							console.error('更新地址失败:', err);
							uni.hideLoading();
							uni.showToast({
								title: '更新地址失败',
								icon: 'none'
							});
						});
				} else {
					// 添加
					this.$api.addAddress(this.addressForm)
						.then(res => {
						    this.loadAddressList()
              uni.hideLoading();
              this.closeForm();
              // 提示
              uni.showToast({
                title: '保存成功',
                icon: 'success'
              });
						})
						.catch(err => {
							console.error('添加地址失败:', err);
							uni.hideLoading();
							uni.showToast({
								title: '添加地址失败',
								icon: 'none'
							});
						});
				}
			},
			// 设为默认地址
			setDefault(id, index) {
				if (!id) {
					uni.showToast({
						title: '地址ID无效',
						icon: 'none'
					});
					return;
				}
				
				uni.showLoading({
					title: '设置中...'
				});
				
				// 调用设置默认地址API
				this.$api.setDefaultAddress({ id, member_user_id : this.userId })
					.then(() => {
            this.loadAddressList()
						uni.hideLoading();
						uni.showToast({
							title: '已设为默认地址',
							icon: 'success'
						});
					})
					.catch(err => {
						console.error('设置默认地址失败:', err);
						uni.hideLoading();
						uni.showToast({
							title: '设置默认地址失败',
							icon: 'none'
						});
					});
			},
			
			// 删除地址
			deleteAddress(id, index) {
				if (!id) {
					uni.showToast({
						title: '地址ID无效',
						icon: 'none'
					});
					return;
				}
				
				uni.showModal({
					title: '提示',
					content: '确定要删除该地址吗？',
					success: (res) => {
						if (res.confirm) {
							uni.showLoading({
								title: '删除中...'
							});
							
							// 调用删除地址API
							this.$api.deleteAddress(id)
								.then(() => {
									// 删除本地列表中的地址
									this.addressList.splice(index, 1);
									uni.hideLoading();
									uni.showToast({
										title: '已删除',
										icon: 'success'
									});
								})
								.catch(err => {
									console.error('删除地址失败:', err);
									uni.hideLoading();
									uni.showToast({
										title: '删除地址失败',
										icon: 'none'
									});
								});
						}
					}
				});
			},
			// 选择地址项 (用于从订单确认页进入选择地址)
			selectAddressItem(item) {
				if (this.isSelect) {
					// 保存选中的地址到本地存储
					uni.setStorageSync('selectedAddress', item);
					
					// 返回上一页
					uni.navigateBack();
				}
			}
		}
	}
</script>

<style lang="scss">
	.container {
		display: flex;
		flex-direction: column;
		padding-bottom: 120rpx;
	}
	
	.address-list {
		flex: 1;
		padding: 20rpx;
	}
	
	.address-item {
		background-color: #fff;
		border-radius: 16rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}
	
	.address-info {
		margin-bottom: 20rpx;
	}
	
	.address-header {
		display: flex;
		align-items: center;
		margin-bottom: 10rpx;
	}
	
	.name {
		font-size: 32rpx;
		font-weight: bold;
		margin-right: 20rpx;
	}
	
	.phone {
		font-size: 28rpx;
		color: #666;
	}
	
	.default-tag {
		font-size: 24rpx;
		color: #fff;
		background-color: #007aff;
		padding: 4rpx 10rpx;
		border-radius: 8rpx;
		margin-left: 20rpx;
	}
	
	.address-detail {
		font-size: 28rpx;
		color: #333;
		line-height: 1.5;
	}
	
	.address-actions {
		display: flex;
		border-top: 1px solid #f0f0f0;
		padding-top: 20rpx;
	}
	
	.action-item {
		flex: 1;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}
	
	.action-item text {
		font-size: 24rpx;
		color: #666;
		margin-top: 8rpx;
	}
	
	.empty-address {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 100rpx 0;
	}
	
	.empty-image {
		width: 200rpx;
		height: 200rpx;
		margin-bottom: 30rpx;
	}
	
	.empty-text {
		font-size: 30rpx;
		color: #999;
	}
	
	.add-btn {
		position: fixed;
		bottom: 30rpx;
		left: 30rpx;
		right: 30rpx;
		height: 80rpx;
		line-height: 80rpx;
		background-color: #007aff;
		color: #fff;
		text-align: center;
		font-size: 32rpx;
		border-radius: 40rpx;
	}
	
	.address-form {
		background-color: #fff;
		padding: 30rpx;
		border-radius: 16rpx 16rpx 0 0;
	}
	
	.form-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 30rpx;
	}
	
	.form-header text {
		font-size: 32rpx;
		font-weight: bold;
	}
	
	.form-content {
		padding-bottom: 30rpx;
	}
	
	.form-item {
		margin-bottom: 30rpx;
	}
	
	.label {
		display: block;
		font-size: 28rpx;
		color: #333;
		margin-bottom: 10rpx;
	}
	
	.input, .region-picker, .textarea {
		width: 100%;
		height: 80rpx;
		background-color: #f5f5f5;
		border-radius: 8rpx;
		padding: 0 20rpx;
		font-size: 28rpx;
		box-sizing: border-box;
	}
	
	.region-picker {
		display: flex;
		align-items: center;
	}
	
	.textarea {
		height: 160rpx;
		padding: 20rpx;
		line-height: 1.5;
	}
	
	.placeholder {
		color: #999;
	}
	
	.checkbox-label {
		display: flex;
		align-items: center;
	}
	
	.checkbox-label text {
		font-size: 28rpx;
		color: #333;
		margin-left: 10rpx;
	}
	
	.form-footer {
		padding-top: 20rpx;
	}
	
	.save-btn {
		width: 100%;
		height: 80rpx;
		line-height: 80rpx;
		background-color: #007aff;
		color: #fff;
		text-align: center;
		font-size: 32rpx;
		border-radius: 40rpx;
	}
</style>